﻿using EkStudio.com.common.session;
using EkStudio.com.common.unit;
using EkStudio.com.ui.unitbill.property.Event;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Xml;

namespace EkStudio.com.common.dbconn
{
    public class HttpConnectUnit
    {
        private log4net.ILog logger = log4net.LogManager.GetLogger(typeof(HttpConnectUnit));

        private User user = null;
        private CookieContainer cookie = null;
        private Cookie SessionCookie = null;
        private const string UserAgent = "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36";
        private const int TimeOut = 20000;//连接超时20秒

        private event KEventHandler EventHandler = null;

        private byte[] AsyncPostParam = null;
        /// <summary>
        /// 图片类型
        /// </summary>
        public const int TYPE_MODULE_NODE_IMAGE = 1;

        /**帐套附件*/
        public const int TYPE_CONFIG_ATTACH_FILE = 2;

        public HttpConnectUnit(User _user)
        {

            this.user = _user;
            ServicePointManager.DefaultConnectionLimit = 200;

        }

        public string AskCompileConfig()
        {
            Dictionary<string, string> parem = new Dictionary<string, string>();
            parem.Add("kt_compile_type", "config");
            string result = this.PostHttp(ProjectUtil.HTTP_COMPILE_URL, parem, "");

            return result;
        }

        public string AskCompileDatabase()
        {
            Dictionary<string, string> parem = new Dictionary<string, string>();
            parem.Add("kt_compile_type", "dataBase");
            string result = this.PostHttp(ProjectUtil.HTTP_COMPILE_URL, parem, "");

            return result;
        }

        public void FileLoadResources(string url, string fileName, string filePath, int fileType)
        {
            String httpUrl = (user.Safety ? "https://" : "http://") + user.Url + url;
            //logger.Info("url=" + httpUrl);
            Encoding encoding = Encoding.UTF8;
            if (user.Safety)
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(httpUrl);
                request.Proxy = null;//关闭代理 否则速度很慢
                request.Timeout = TimeOut;
                CookieContainer ckContainer = null;
                if (cookie == null)
                {
                    cookie = new CookieContainer();
                    ckContainer = cookie;
                }
                else
                {
                    ckContainer = new CookieContainer();
                    ckContainer.Add(this.SessionCookie);
                }
                request.CookieContainer = ckContainer;
                request.ProtocolVersion = HttpVersion.Version10;
                request.Method = "POST";
                request.KeepAlive = true;
                request.AllowAutoRedirect = true;
                request.Accept = "*/*";
                request.ContentType = "application/x-www-form-urlencoded";
                //模拟WIN7 64  chrome浏览器登录
                request.UserAgent = UserAgent;

                Dictionary<string, string> param = new Dictionary<string, string>();
                param.Add("fileName", fileName);
                param.Add("fileType", Convert.ToString(fileType));
                StringBuilder text = new StringBuilder();

                if (param != null && param.Count > 0)
                {
                    foreach (string key in param.Keys)
                    {
                        if (text.Length > 0) text.Append("&");
                        text.Append(key).Append("=").Append(param[key]);
                    }
                }
                byte[] array = encoding.GetBytes(text.ToString());
                request.ContentLength = array.Length;
                try
                {
                    Stream reqStream = null;
                    try
                    {
                        reqStream = request.GetRequestStream();
                        if (array.Length > 0) reqStream.Write(array, 0, array.Length);

                    }
                    finally
                    {
                        if (reqStream != null) reqStream.Close();
                    }
                    HttpWebResponse response = null;
                    try
                    {
                        response = (HttpWebResponse)request.GetResponse();
                        Stream reader = null;
                        try
                        {
                            reader = response.GetResponseStream();
                            FileStream fs = new FileStream(filePath, FileMode.Create);
                            byte[] buffer = new byte[4096];
                            int readEnd = 0;
                            while ((readEnd = reader.Read(buffer, 0, buffer.Length)) != 0)
                            {
                                fs.Write(buffer, 0, readEnd);
                            }
                            fs.Flush();
                            fs.Close();
                        }
                        finally
                        {
                            if (reader != null) reader.Close();
                        }

                    }
                    finally
                    {
                        try
                        {
                            if (response != null) response.Close();
                        }
                        catch
                        {

                        }

                    }

                }
                catch (Exception e)
                {
                    logger.Error("HTTP POST Error :" + e.Message);
                }

                request.Abort();
            }
            catch (Exception e)
            {
                logger.Error("HTTP POST Error :" + e.Message);
            }
            return;
        }
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="url"></param>
        /// <param name="fileName"></param>
        /// <param name="filePath"></param>
        /// <param name="fileType"></param>
        /// <returns></returns>
        public bool FileUpLoadResources(string url, string fileName, string filePath, int fileType)
        {
            bool result = false;
            string httpUrl = (user.Safety ? "https://" : "http://") + user.Url + url;
            logger.Info("url==" + httpUrl);
            Encoding encoding = Encoding.UTF8;
            if (user.Safety)
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            string boundary = "------------7d318fd100112";
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(httpUrl);
                request.Proxy = null;//关闭代理 否则速度很慢
                request.Timeout = TimeOut;
                CookieContainer ckContainer = null;
                if (cookie == null)
                {
                    cookie = new CookieContainer();
                    ckContainer = cookie;
                }
                else
                {
                    ckContainer = new CookieContainer();
                    ckContainer.Add(this.SessionCookie);
                }
                request.CookieContainer = ckContainer;
                request.ProtocolVersion = HttpVersion.Version10;
                request.Method = "POST";
                request.KeepAlive = true;
                request.AllowAutoRedirect = true;
                request.Accept = "*/*";
                request.AllowWriteStreamBuffering = false;
                request.ContentType = "multipart/form-data; boundary=" + boundary;
                //模拟WIN7 64  chrome浏览器登录
                request.UserAgent = UserAgent;

                StringBuilder sb = new StringBuilder();
                //传值fileName
                sb.Append("--").Append(boundary).Append("\r\n");
                sb.Append("Content-Disposition: form-data; name=\"fileName\" \r\n");
                sb.Append("\r\n");
                sb.Append(fileName).Append("\r\n");
                //传值fileType
                sb.Append("--").Append(boundary).Append("\r\n");  //分隔标记
                sb.Append("Content-Disposition: form-data; name=\"fileType\" \r\n");
                sb.Append("\r\n");
                sb.Append(fileType).Append("\r\n");
                //传输文件
                sb.Append("--").Append(boundary).Append("\r\n");  //分隔标记
                sb.Append("Content-Disposition: form-data; name=\"loadFile\";filename=\"").Append(filePath).Append("\" \r\n");
                sb.Append("Content-Type:application/octet-stream \r\n");
                sb.Append("\r\n");
                //前参数
                byte[] beforeHeadBytes = Encoding.UTF8.GetBytes(sb.ToString());
                //后参数标记
                byte[] boundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n\r\n");

                FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

                long length = beforeHeadBytes.Length + fileStream.Length + boundaryBytes.Length;

                request.ContentLength = length;
                Stream reqStream = null;
                try
                {
                    reqStream = request.GetRequestStream();
                    reqStream.Write(beforeHeadBytes, 0, beforeHeadBytes.Length);
                    byte[] buffer = new byte[4096];
                    int bytesRead = 0;
                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        reqStream.Write(buffer, 0, bytesRead);
                    }
                    reqStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                }
                finally
                {
                    if (reqStream != null) reqStream.Close();
                    try
                    {
                        fileStream.Close();
                    }
                    catch { }

                }
                HttpWebResponse response = null;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                    StreamReader reader = null;
                    try
                    {
                        reader = new StreamReader(response.GetResponseStream(), encoding);
                        string xml = reader.ReadToEnd().ToString();
                        //logger.Info(xml);
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(xml);
                        XmlElement root = doc.DocumentElement;
                        XmlNode node = root.SelectSingleNode("result");
                        if (node != null)
                        {
                            string typestr = node.InnerText;
                            if (typestr == "0")
                            {
                                result = true;
                            }
                        }
                    }
                    finally
                    {
                        if (reader != null) reader.Close();
                    }

                }
                finally
                {
                    try
                    {
                        if (response != null) response.Close();
                    }
                    catch
                    {

                    }

                }

            }
            catch (Exception e)
            {
                logger.Error("上传文件异常", e);
            }


            return result;
        }
        /// <summary>
        /// 登录服务器 0:登录成功 1：用户名不存在 2：密码错误 3：用户名已被占用 -1：地址不可用
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <returns></returns>
        public int Login(string userName, string password)
        {
            int ResultType = -1;
            String url = ProjectUtil.HTTP_LOGINURL;

            Dictionary<string, string> hash = new Dictionary<string, string>();
            hash.Add("userName", userName);
            hash.Add("password", password);
            hash.Add("machine", user.Machine);
            hash.Add("address", user.Ipv4add);

            string result = this.PostHttp(url, hash, "");

            if (result.Length > 0)
            {
                XmlDocument xml = new XmlDocument();
                try
                {
                    xml.LoadXml(result);
                    XmlElement root = xml.DocumentElement;
                    XmlNode node = root.SelectSingleNode("/root/result");
                    if (node != null)
                    {
                        XmlElement element = (XmlElement)node;
                        if (element.InnerText != null)
                        {
                            try
                            {
                                ResultType = Int32.Parse(element.InnerText);
                            }
                            catch
                            {
                                ResultType = -1;
                            }
                        }
                        if (ResultType == 0)
                        {
                            node = root.SelectSingleNode("/root/session");
                            if (node != null) user.Sessionid = node.InnerText;
                            node = root.SelectSingleNode("/root/userId");
                            if (node != null) user.UserId = node.InnerText;
                            node = root.SelectSingleNode("/root/realName");
                            if (node != null) user.RealName = node.InnerText;

                        }
                        //logger.Info(user.ToString());
                    }
                }
                catch
                {

                }

            }

            return ResultType;
        }

        public void LogOut()
        {
            string url = ProjectUtil.HTTP_LOGINOUT_URL;
            string result = this.PostHttp(url, null, "");
            //logger.Info("LogOut" + result);

        }

        public string GetHttp(string url,Dictionary<string,string> param,string contentType)
        {
            string result = "";
            String httpUrl = (user.Safety ? "https://" : "http://") + user.Url + url;
            //logger.Info("url=" + httpUrl);
            bool firstLoad = false;
            Encoding encoding = Encoding.UTF8;
            if (user.Safety)
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            if (param != null && param.Count > 0)
            {
                StringBuilder text = new StringBuilder();
                foreach (string key in param.Keys)
                {
                    if (text.Length > 0) text.Append("&");
                    text.Append(key).Append("=").Append(param[key]);
                }
                if (text.Length > 0)
                {
                    httpUrl = string.Format("{0}?{1}", httpUrl, text.ToString());
                }
            }
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(httpUrl);
                request.Proxy = null;//关闭代理 否则速度很慢
                request.Timeout = TimeOut;
                CookieContainer ckContainer = null;
                if (cookie == null)
                {
                    cookie = new CookieContainer();
                    firstLoad = true;
                    ckContainer = cookie;
                }
                else
                {
                    ckContainer = new CookieContainer();
                    ckContainer.Add(this.SessionCookie);
                }
                request.CookieContainer = ckContainer;
                request.ProtocolVersion = HttpVersion.Version10;
                request.Method = "GET";
                request.KeepAlive = true;
                request.AllowAutoRedirect = true;
                request.Accept = "*/*";
                if (contentType != "")
                {
                    request.ContentType = contentType;
                }
                else
                {
                    request.ContentType = "text/xml";
                }
                //模拟WIN7 64  chrome浏览器登录
                request.UserAgent = UserAgent;
                HttpWebResponse response = null;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                    StreamReader reader = null;
                    try
                    {
                        reader = new StreamReader(response.GetResponseStream(), encoding);
                        result = reader.ReadToEnd();

                    }
                    finally
                    {
                        if (reader != null) reader.Close();
                    }

                }
                finally
                {
                    try
                    {
                        if (response != null) response.Close();
                    }
                    catch
                    {

                    }

                }

                request.Abort();
            }
            catch(Exception e)
            {
                logger.Error("HTTP POST Error :" + e.Message);
            }
            if (firstLoad)
            {
                List<Cookie> list = this.GetAllCookies(cookie);
                if (list != null && list.Count > 0)
                {
                    //StringBuilder sb = new StringBuilder();
                    foreach (Cookie ck in list)
                    {
                        if (ck.Name == "JSESSIONID")
                        {
                            this.SessionCookie = ck;
                        }
                    }
                }
            }
            return result;
        }
        /// <summary>
        /// 远程Post数据
        /// </summary>
        /// <param name="url">访问全地址</param>
        /// <param name="param">传值参数</param>
        /// <param name="contentType">返回类型</param>
        /// <returns></returns>
        public string PostHttp(String url, Dictionary<string, string> param, string contentType)
        {
            string result = "";
            String httpUrl = (user.Safety ? "https://" : "http://") + user.Url + url;
            //logger.Info("url=" + httpUrl);
            bool firstLoad = false;
            Encoding encoding = Encoding.UTF8;
            if (user.Safety)
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(httpUrl);
                request.Proxy = null;//关闭代理 否则速度很慢
                request.Timeout = TimeOut;
                CookieContainer ckContainer = null;
                if (cookie == null)
                {
                    cookie = new CookieContainer();
                    firstLoad = true;
                    ckContainer = cookie;
                }
                else
                {
                    ckContainer = new CookieContainer();
                    ckContainer.Add(this.SessionCookie);
                }
                request.CookieContainer = ckContainer;
                request.ProtocolVersion = HttpVersion.Version10;
                request.Method = "POST";
                request.KeepAlive = true;
                request.AllowAutoRedirect = true;
                request.Accept = "*/*";
                if (contentType != "")
                {
                    request.ContentType = contentType;
                }
                else
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                }
                //模拟WIN7 64  chrome浏览器登录
                request.UserAgent = UserAgent;
                StringBuilder text = new StringBuilder();
                if (param != null && param.Count > 0)
                {
                    foreach (string key in param.Keys)
                    {
                        if (text.Length > 0) text.Append("&");
                        text.Append(key).Append("=").Append(param[key]);
                    }
                }
                byte[] array = encoding.GetBytes(text.ToString());
                request.ContentLength = array.Length;
                try
                {
                    Stream reqStream = null;
                    try
                    {
                        reqStream = request.GetRequestStream();
                        if (array.Length > 0) reqStream.Write(array, 0, array.Length);

                    }
                    finally
                    {
                        if (reqStream != null) reqStream.Close();
                    }
                    HttpWebResponse response = null;
                    try
                    {
                        response = (HttpWebResponse)request.GetResponse();
                        StreamReader reader = null;
                        try
                        {
                            reader = new StreamReader(response.GetResponseStream(), encoding);
                            result = reader.ReadToEnd().ToString();

                        }
                        finally
                        {
                            if (reader != null) reader.Close();
                        }

                    }
                    finally
                    {
                        try
                        {
                            if (response != null) response.Close();
                        }
                        catch
                        {

                        }

                    }

                }
                catch (Exception e)
                {
                    logger.Error("HTTP POST Error :" + e.Message);
                }

                request.Abort();
            }
            catch (Exception e)
            {
                logger.Error("HTTP POST Error :" + e.Message);
            }

            if (firstLoad)
            {
                List<Cookie> list = this.GetAllCookies(cookie);
                if (list != null && list.Count > 0)
                {
                    //StringBuilder sb = new StringBuilder();
                    foreach (Cookie ck in list)
                    {
                        if (ck.Name == "JSESSIONID")
                        {
                            this.SessionCookie = ck;
                        }
                    }
                }
            }

            return result;
        }
        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="billName"></param>
        /// <param name="billType"></param>
        /// <param name="xml"></param>
        /// <returns></returns>
        public string SaveXmlBean(string billName, int billType, string xml)
        {
            string result = "";
            string url = ProjectUtil.HTTP_SAVEXML_URL + "?kt_billName=" + billName + "&kt_billType=" + billType;
            String httpUrl = (user.Safety ? "https://" : "http://") + user.Url + url;
            //logger.Info("url=" + httpUrl);
            Encoding encoding = Encoding.UTF8;
            if (user.Safety)
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(httpUrl);
                request.Proxy = null;//关闭代理 否则速度很慢
                request.Timeout = TimeOut;
                if (cookie == null) cookie = new CookieContainer();
                request.CookieContainer = cookie;
                request.ProtocolVersion = HttpVersion.Version10;
                request.Method = "POST";
                request.KeepAlive = true;
                request.AllowAutoRedirect = true;
                request.Accept = "*/*";
                request.ContentType = "text/xml";
                //模拟WIN7 64  chrome浏览器登录
                request.UserAgent = UserAgent;

                byte[] array = encoding.GetBytes(xml);
                request.ContentLength = array.Length;
                try
                {
                    Stream reqStream = null;
                    try
                    {
                        reqStream = request.GetRequestStream();
                        if (array.Length > 0) reqStream.Write(array, 0, array.Length);

                    }
                    finally
                    {
                        if (reqStream != null) reqStream.Close();
                    }
                    HttpWebResponse response = null;
                    try
                    {
                        response = (HttpWebResponse)request.GetResponse();
                        StreamReader reader = null;
                        try
                        {
                            reader = new StreamReader(response.GetResponseStream(), encoding);
                            result = reader.ReadToEnd().ToString();
                        }
                        finally
                        {
                            if (reader != null) reader.Close();
                        }
                    }
                    finally
                    {
                        try
                        {
                            if (response != null) response.Close();
                        }
                        catch
                        {

                        }

                    }

                }
                catch (Exception e)
                {
                    logger.Error("HTTP POST Error :" + e.Message);
                }

                request.Abort();
            }
            catch (Exception e)
            {
                logger.Error("HTTP POST Error :" + e.Message);
            }
            return result;
        }


        public string ResourcesXmlBean(string billName, string caption, int billType, ref bool ReadOnly, Dictionary<string, string> param)
        {
            string result = "";
            string FileConfigPath = ProjectUtil.getBillPath(billName, billType);
            if (FileConfigPath.IndexOf(".xml") == -1) FileConfigPath = FileConfigPath + ".xml";
            if (param == null) { param = new Dictionary<string, string>(); }
            Dictionary<string, string> tParam = new Dictionary<string, string>();
            ReadOnly = false;
            tParam.Add("key", billName);
            tParam.Add("caption", caption);
            tParam.Add("fileName", FileConfigPath);
            tParam.Add("readOnly", "false");
            if (billType == ProjectUtil.TYPE_PROJECT_MENU || billType == ProjectUtil.TYPE_PROJECT_VERSION)//目录单据无需要验证
            {
                tParam.Add("validation", "false");
            }
            else
            {
                tParam.Add("validation", "true");
            }
            tParam.Add("billType", billType.ToString());

            if (param != null && param.Count > 0)
            {
                foreach(string key in param.Keys)
                {
                    
                    if (tParam.ContainsKey(key))
                    {
                        tParam[key] = param[key];
                    }
                    else
                    {
                        tParam.Add(key, param[key]);
                    }
                }
            }

            //请求数据
            string xml = this.PostHttp(ProjectUtil.HTTP_RESOURCES_URL, tParam, "");

            XmlDocument XmlDoc = new XmlDocument();
            try
            {
                XmlDoc.LoadXml(xml);

            }
            catch (Exception e)
            {
                logger.Error("返回Xml格式化失败:" + e.StackTrace + " xml=" + xml);
                throw new Exception("返回Xml格式化失败" ,e);
            }
            if (XmlDoc.HasChildNodes)
            {
                XmlElement XmlRoot = XmlDoc.DocumentElement;
                #region 返回值为状态提示
                if (XmlRoot.Name == "error")
                {
                    XmlNode node = XmlRoot.SelectSingleNode("/error/result");
                    if (node != null)
                    {
                        int value = -1;
                        try
                        {
                            value = int.Parse(node.InnerText);
                        }
                        catch { }
                        if (value == -1)
                        {
                            throw new Exception(string.Format("验证资源失败[{0}]", billName));
                        }
                        else if (value == 1)
                        {
                            throw new Exception("Session失效,请重新登录");
                        }
                        else if (value == 3)
                        {
                            throw new Exception("当前资源不存在");
                        }
                        else
                        {
                            if (value == 2) { ReadOnly = true; }
                            param["validation"] = "false";
                            xml = this.PostHttp(ProjectUtil.HTTP_RESOURCES_URL, param, "");
                            XmlDoc.RemoveAll();
                            try
                            {
                                XmlDoc.LoadXml(xml);
                            }
                            catch (Exception e)
                            {
                                logger.Error("加载表单XML数据格格式失败:" + xml);
                                throw new Exception("加载表单XML数据格格式失败:" + e.Message);
                            }
                            if (XmlDoc.HasChildNodes)
                            {
                                result = XmlDoc.OuterXml;
                            }
                        }

                    }
                }
                #endregion
                else
                #region 返回值为xml内容
                {
                    if (XmlDoc.HasChildNodes)
                    {
                        result = XmlDoc.OuterXml;
                    }
                }
                #endregion
            }
            return result;
        }
        /// <summary>
        /// 异步加载数据
        /// </summary>
        /// <param name="billName"></param>
        /// <param name="caption"></param>
        /// <param name="billType"></param>
        /// <param name="ReadOnly"></param>
        /// <param name="param"></param>
        public void AsyncResourcesXmlBean(string billName, string caption, int billType, ref bool ReadOnly, Dictionary<string, string> param, KEventHandler CanFunncation)
        {
            string FileConfigPath = ProjectUtil.getBillPath(billName, billType);
            if (FileConfigPath.IndexOf(".xml") == -1) FileConfigPath = FileConfigPath + ".xml";
            if (param == null) { param = new Dictionary<string, string>(); }
            param.Add("key", billName);
            param.Add("caption", caption);
            param.Add("fileName", FileConfigPath);
            param.Add("readOnly", "false");
            if (billType == ProjectUtil.TYPE_PROJECT_MENU || billType == ProjectUtil.TYPE_PROJECT_VERSION)//目录单据无需要验证
            {
                param.Add("validation", "false");
                ReadOnly = false;
            }
            else
            {
                param.Add("validation", ReadOnly?"true":"false");
            }
            param.Add("billType", billType.ToString());
            //首先同步加载判断是否只读
            if (ReadOnly)
            {
                ReadOnly = false ;
                #region 同步验证数据是否可加载
                //请求数据
                string xml = this.PostHttp(ProjectUtil.HTTP_RESOURCES_URL, param, "");
                XmlDocument XmlDoc = new XmlDocument();
                try
                {
                    XmlDoc.LoadXml(xml);
                    XmlElement XmlRoot = XmlDoc.DocumentElement;
                    if (XmlRoot.Name == "error")
                    {
                        XmlNode node = XmlRoot.SelectSingleNode("/error/result");
                        if (node != null)
                        {
                            int value = -1;
                            try
                            {
                                value = Convert.ToInt32(node.InnerText);
                            }
                            catch { }
                            if (value == -1)
                            {
                                CanFunncation(this, new PropertyDataEvent("Error", string.Format("验证资源失败[{0}]", billName)));
                            }
                            else if (value == 1)
                            {
                                CanFunncation(this, new PropertyDataEvent("Error", "Session失效,请重新登录"));
                            }
                            else if (value == 3)
                            {
                                CanFunncation(this, new PropertyDataEvent("Error", string.Format("请求的资源不存在[{0}]", billName)));
                            }
                            else
                            {
                                if (value == 2) { ReadOnly = true; }
                                param["validation"] = "false";
                                AsyncPost(ProjectUtil.HTTP_RESOURCES_URL, param, "", CanFunncation);
                            }

                        }
                        else
                        {
                            CanFunncation(this, new PropertyDataEvent("Error", string.Format("验证资源失败[{0}]", billName)));
                        }
                    }
                    else
                    {
                        CanFunncation(this, new PropertyDataEvent("Error", string.Format("验证资源失败[{0}]", billName)));
                    }
                }
                catch
                {
                    CanFunncation(this, new PropertyDataEvent("Error", string.Format("验证资源失败[{0}]", billName)));
                }
                #endregion
            }
            else
            {
                param["validation"] = "false";
                AsyncPost(ProjectUtil.HTTP_RESOURCES_URL, param, "", CanFunncation);
            }

            
        }
        /// <summary>
        /// 释放模块占用
        /// </summary>
        /// <param name="key"></param>
        /// <param name="caption"></param>
        /// <param name="type"></param>
        public void ReleaseModule(string key, string caption, int type)
        {
            Dictionary<string, string> param = new Dictionary<string, string>();
            param.Add("kt_billName", key);
            param.Add("kt_operate", "close");
            string temp = this.PostHttp(ProjectUtil.HTTP_SAFETY_URL, param, "");

        }

        private bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }



        #region 异步post方法

        /// <summary>
        /// 异步Post
        /// </summary>
        public void AsyncPost(String url, Dictionary<string, string> param, string contentType, KEventHandler CanFunncation)
        {
            String httpUrl = (user.Safety ? "https://" : "http://") + user.Url + url;
            //logger.Info("url=" + httpUrl);
            Encoding encoding = Encoding.UTF8;
            if (user.Safety)
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
            }

            //异步回调事件
            if (CanFunncation != null)
            {
                EventHandler = CanFunncation;
            }
            try
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(httpUrl);
                request.Proxy = null;//关闭代理 否则速度很慢
                request.Timeout = TimeOut;
                CookieContainer ckContainer = null;
                if (cookie == null)
                {
                    cookie = new CookieContainer();
                    ckContainer = cookie;
                }
                else
                {
                    ckContainer = new CookieContainer();
                    ckContainer.Add(this.SessionCookie);
                }
                request.CookieContainer = ckContainer;
                request.ProtocolVersion = HttpVersion.Version10;
                request.Method = "POST";
                request.KeepAlive = true;
                request.AllowAutoRedirect = true;
                request.Accept = "*/*";
                if (contentType != "")
                {
                    request.ContentType = contentType;
                }
                else
                {
                    request.ContentType = "application/x-www-form-urlencoded";
                }
                //模拟WIN7 64  chrome浏览器登录
                request.UserAgent = UserAgent;
                StringBuilder text = new StringBuilder();
                if (param != null && param.Count > 0)
                {
                    foreach (string key in param.Keys)
                    {
                        if (text.Length > 0) text.Append("&");
                        text.Append(key).Append("=").Append(param[key]);
                    }
                }
                AsyncPostParam = encoding.GetBytes(text.ToString());
                request.ContentLength = AsyncPostParam.Length;
                try
                {
                    request.BeginGetRequestStream(new AsyncCallback(AsyncRequestStreamCallBack), request);

                }
                catch (Exception e)
                {
                    logger.Error("HTTP POST Error :" + e.Message, e);
                    if (EventHandler != null)
                    {
                        EventHandler(this, new PropertyDataEvent("Error", "连接服务器加载失败1"));
                    }
                }
            }
            catch (Exception e)
            {
                logger.Error("HTTP POST Error :" + e.Message, e);
                if (EventHandler != null)
                {
                    EventHandler(this, new PropertyDataEvent("Error", "连接服务器加载失败2"));
                }
            }
        }
        /// <summary>
        /// 异步传输参数
        /// </summary>
        /// <param name="result"></param>
        private void AsyncRequestStreamCallBack(IAsyncResult result)
        {
            try
            {
                HttpWebRequest request = (HttpWebRequest)result.AsyncState;
                Stream reqStream = request.EndGetRequestStream(result);
                reqStream.Write(this.AsyncPostParam, 0, AsyncPostParam.Length);
                reqStream.Close();
                request.BeginGetResponse(new AsyncCallback(AsyncCallPost), request);
            }
            catch (Exception e)
            {
                logger.Error("异步Post传输参数异常", e);
                if (this.EventHandler != null)
                {
                    EventHandler(this, new PropertyDataEvent("Error", "连接服务器加载失败3"));
                }
            }

        }

        private void AsyncCallPost(IAsyncResult result)
        {
            StringBuilder xml = new StringBuilder();
            StreamReader reader = null;
            try
            {
                try
                {
                    HttpWebRequest req = (HttpWebRequest)result.AsyncState;
                    HttpWebResponse response = (HttpWebResponse)req.EndGetResponse(result);
                    reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    xml.Append(reader.ReadToEnd().ToString());
                    if (EventHandler != null) EventHandler(this, new PropertyDataEvent("OK", xml.ToString()));
                }
                catch
                {
                    if(EventHandler!=null) EventHandler(this, new PropertyDataEvent("Error", "连接服务器加载失败4"));
                }

            }
            finally
            {
                if (reader != null) reader.Close();
            }
            EventHandler = null;
        }

        #endregion

        private List<Cookie> GetAllCookies(CookieContainer cc)
        {
            List<Cookie> lstCookies = new List<Cookie>();

            Hashtable table = (Hashtable)cc.GetType().InvokeMember("m_domainTable",
            System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField |
            System.Reflection.BindingFlags.Instance, null, cc, new object[] { });

            foreach (object pathList in table.Values)
            {
                SortedList lstCookieCol = (SortedList)pathList.GetType().InvokeMember("m_list",
                System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField
                | System.Reflection.BindingFlags.Instance, null, pathList, new object[] { });
                foreach (CookieCollection colCookies in lstCookieCol.Values)
                    foreach (Cookie c in colCookies) lstCookies.Add(c);
            }

            return lstCookies;
        }

    }
}

